﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using MvcContrib.Sorting;
using MvcContrib.UI.Grid;
using QDT.Common;
using QDT.Common.Data;
using QDT.Core.Domain;
using QDT.MVC.Security;
using QDT.Web.Admin.Helper;
using QDT.Web.Admin.Models;

namespace QDT.Web.Admin.Controllers {
    [SecurityModule(Name = "文章管理")]
    public class ArticleController : BaseController {
        //
        // GET: /Article/
        [SecurityNode(Name = "文章列表")]
        public ActionResult Index(int? id, int? cateId, string title, int? page, GridSortOptions sort) {
            ViewData["sort"] = sort;
            Expression<Func<Article, bool>> filter = PredicateExtensionses.True<Article>();
            if (id.HasValue && id.Value != 0)
            {
                filter = filter.And(o => o.ID == id.Value);
            }
            if (cateId.HasValue && cateId.Value != 0) {
                filter = filter.And(o => o.CateId == cateId.Value);
            }
            if (!string.IsNullOrEmpty(title)) {
                filter = filter.And(o => o.Title.Contains(title));
            }
            filter = filter.And(o => !o.IsDelete);
            const int pageSize = 20;
            int pageNumber = page ?? 1;
            IPagedList<Article> source =
                DbProvider.D<Article>().Where(filter).OrderBy(sort.Column, sort.Direction == SortDirection.Descending).
                    ToPagedList(pageNumber - 1, pageSize);
            List<ArticleCate> cate =
                DbProvider.D<ArticleCate>().Where(
                    o => (o.ParentId == null || o.ParentId.Value == 0) && o.IsEffect && !o.IsDelete).ToList();
            IList<ArticleCateModel> cateModel = cate.ToModelList();
            ViewData["CateModel"] = cateModel.ToTreeNode();
            return View(source.ToModelList());
        }

        [SecurityNode(Name = "文章回收站")]
        public ActionResult Trash(int? page, GridSortOptions sort) {
            ViewData["sort"] = sort;
            Expression<Func<Article, bool>> filter = PredicateExtensionses.True<Article>();
            filter = filter.And(o => o.IsDelete);
            const int pageSize = 20;
            int pageNumber = page ?? 1;
            IPagedList<Article> source = DbProvider.D<Article>().Where(filter).OrderBy(sort.Column,
                                                                                       sort.Direction
                                                                                       == SortDirection.Descending).
                ToPagedList(pageNumber - 1, pageSize);
            return View(source.ToModelList());
        }

        [HttpGet]
        [SecurityNode(Name = "新增文章页面")]
        public ActionResult Add() {
            List<ArticleCate> cate =
                DbProvider.D<ArticleCate>().Where(
                    o => (o.ParentId == null || o.ParentId.Value == 0) && o.IsEffect && !o.IsDelete).ToList();
            IList<ArticleCateModel> cateModel = cate.ToModelList();
            ViewData["CateModel"] = cateModel.ToTreeNode();
            return View();
        }

        [HttpPost]
        [SecurityNode(Name = "新增文章")]
        [ValidateInput(false)]
        public ActionResult PostAdd(ArticleModel model) {
            Article entity = model.ToEntity();
            DbProvider.Add(entity);
            DbProvider.SaveChanges();
            return Success("操作成功");
        }

        [HttpGet]
        [SecurityNode(Name = "编辑文章页面")]
        public ActionResult Edit(int id) {
            var data = DbProvider.GetByID<Article>(id);
            ArticleModel model = data.ToModel();
             List<ArticleCate> cate =
                DbProvider.D<ArticleCate>().Where(
                    o => (o.ParentId == null || o.ParentId.Value == 0) && o.IsEffect && !o.IsDelete).ToList();
            IList<ArticleCateModel> cateModel = cate.ToModelList();
            ViewData["CateModel"] = cateModel.ToTreeNode();
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [SecurityNode(Name = "编辑文章")]
        public ActionResult PostEdit(ArticleModel model) {
            var entity = DbProvider.GetByID<Article>(model.Id);
            entity.Title = model.Title;
            entity.SubTitle = model.SubTitle;
            entity.Brief = model.Brief;
            entity.RelUrl = model.RelUrl;
            entity.UName = model.UName;
            entity.Sort = model.Sort;
            entity.CateId = model.CateId;
            entity.IsEffect = model.IsEffect;
            entity.Content = model.Content;
            entity.SeoTitle = model.SeoTitle;
            entity.SeoKeyWord = model.SeoKeyWord;
            entity.SeoDescription = model.SeoDescription;
            entity.Photo = model.photo;
            //entity.UpdateAdminId =
            entity.UpdateTime = DateTime.Now;
            DbProvider.Update(entity);
            DbProvider.SaveChanges();
            return Success("操作成功");
        }

        [HttpPost]
        [SecurityNode(Name = "删除文章")]
        public JsonResult Delete(int[] id) {
            try {
                if (!id.Any()) {
                    return null;
                }
                foreach (int i in id) {
                    var data = DbProvider.GetByID<Article>(i);
                    data.IsDelete = true;
                }
                DbProvider.SaveChanges();
                return Json(new {
                    Status = true, Info = "操作成功"
                });
            }
            catch (Exception ex) {
                return Json(new {
                    Status = false, Info = ex.Message
                });
            }
        }

        [HttpPost]
        [SecurityNode(Name = "永久删除文章")]
        public JsonResult ForeverDel(int[] id) {
            try {
                if (!id.Any()) {
                    return null;
                }
                foreach (int i in id) {
                    int tmpId = i;
                    DbProvider.Delete<Article>(o => o.ID == tmpId);
                }
                DbProvider.SaveChanges();
                return Json(new {
                    Status = true,
                    Info = "操作成功"
                });
            }
            catch (Exception ex) {
                return Json(new {
                    Status = false,
                    Info = ex.Message
                });
            }
        }

        [HttpPost]
        [SecurityNode(Name = "恢复文章")]
        public JsonResult Restore(int[] id) {
            try {
                if (!id.Any()) {
                    return null;
                }
                foreach (int i in id) {
                    var data = DbProvider.GetByID<Article>(i);
                    data.IsDelete = false;
                }
                DbProvider.SaveChanges();
                return Json(new {
                    Status = true, Info = "操作成功"
                });
            }
            catch (Exception ex) {
                return Json(new {
                    Status = false, Info = ex.Message
                });
            }
        }
    }
}